package com.ytjj.qmyx.users.controller.taoxingou;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.WxUtils;
import com.ytjj.common.utils.*;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.model.PayConfigDto;
import com.ytjj.qmyx.users.constants.CompanyConstant;
import com.ytjj.qmyx.users.constants.WxConstants;
import com.ytjj.qmyx.users.model.dto.WeixinPhoneDecryptInfo;
import com.ytjj.qmyx.users.model.request.GetH5WxJsSdkRequest;
import com.ytjj.qmyx.users.model.request.RegisterRequest;
import com.ytjj.qmyx.users.service.LoginService;
import com.ytjj.qmyx.users.service.RedisService;
import com.ytjj.qmyx.users.service.UsersService;
import com.ytjj.qmyx.users.utils.AESForWeixinGetPhoneNumber;
import com.ytjj.qmyx.users.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * @Description XXXX优品登录接口
 */
@Slf4j
@RestController
@RequestMapping("/txg/login")
@Validated
public class TxgLoginController extends BaseController {

    private final LoginService loginService;
    private final RedisService redisService;
    private final MallClient mallClient;
    private final UsersService usersService;


    public TxgLoginController(LoginService loginService, RedisService redisService, MallClient mallClient, UsersService usersService) {
        this.loginService = loginService;
        this.redisService = redisService;
        this.mallClient = mallClient;
        this.usersService = usersService;
    }

    /**
     * 获取h5微信js授权sdk
     * @param request
     * @return
     */
    @PostMapping("getH5WxJsSdk")
    public CommonResult getH5WxJsSdk(@RequestBody GetH5WxJsSdkRequest request) {
        PayConfigDto payConfigDto = mallClient.getPayConfigByCompany(CompanyConstant.PLATFORM_TXG);
        return CommonResult.success(WxUtils.getJsSdk(payConfigDto.getTicket(), payConfigDto.getPayPageUri(),payConfigDto.getSubAppId()));
    }

    /**
     * h5 获取公众号用户信息
     *
     * @return
     */
    @GetMapping("/getH5WxUid")
    public CommonResult getH5WxUid(@RequestParam("code") String code) {
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", WxConstants.WX_MWEB_APPID_TXG);
        param.put("secret", WxConstants.WX_MWEB_SECRET_TXG);
        param.put("code", code);
        param.put("grant_type", WxConstants.WX_APPLET_LOGIN_GRANT_TYPE);
        // 发送请求
        String wxResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        log.info("登陆响应：json:{}", JSONObject.toJSONString(jsonObject));
        return CommonResult.success(jsonObject);
    }


    /**
     * 小程序获取用户Uid
     *
     * @return
     */
    @GetMapping("/getWxUid")
    public CommonResult getWxUid(@RequestParam("code") String code) {
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", WxConstants.WX_APPLET_APPID_TXG);
        param.put("secret", WxConstants.WX_APPLET_SECRET_TXG);
        param.put("js_code", code);
        param.put("grant_type", WxConstants.WX_APPLET_LOGIN_GRANT_TYPE);
        // 发送请求
        String wxResult = HttpClientUtil.doGet(WxConstants.WX_APPLET_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        log.info("登陆响应：json:{}", JSONObject.toJSONString(jsonObject));
        return CommonResult.success(jsonObject);
    }

    /**
     * APP获取用户Token
     *
     * @return
     */
    @GetMapping("/getAppWxToken")
    public CommonResult getAppWxToken(@RequestParam("code") String code) {
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", WxConstants.WX_APP_ID_TXG);
        param.put("secret", WxConstants.WX_APP_SECRET_TXG);
        param.put("code", code);
        param.put("grant_type", WxConstants.WX_APPLET_LOGIN_GRANT_TYPE);
        // 发送请求
        String wxResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        log.info("登陆响应：json:{}", JSONObject.toJSONString(jsonObject));
        try {
            UsersResponse usersResponse = this.getCurrentUser();
            if (null != usersResponse) {
                log.info("===openId==={}", jsonObject.get("openid").toString());
                usersService.updateUserWxOpenId(usersResponse.getId(), jsonObject.get("openid").toString());
            }
        } catch (Exception e) {
            log.error("===异常==={}", e);
        }

        return CommonResult.success(jsonObject);
    }

    /**
     * APP获取用户信息
     * @param accessToken
     * @param openid
     * @return
     */
    @GetMapping("/getAppWxUserinfo")
    public CommonResult getAppWxUserinfo(@RequestParam("accessToken") String accessToken,
                                         @RequestParam("openid") String openid){
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("access_token",accessToken);
        param.put("openid", openid);
        param.put("lang", "zh_CN");
        // 发送请求
        String wxResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo", param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        log.info("登陆响应：json:{}", JSONObject.toJSONString(jsonObject));
        return CommonResult.success(jsonObject);
    }

    /**
     * 微信手机号登录
     * @param registerRequest
     * @return
     */
    @PostMapping("/wxPhoneLogin")
    public CommonResult wxPhoneLogin(@RequestBody RegisterRequest registerRequest){
        registerRequest.setIp(IPUtil.getIpAddress(TokenUtil.getRequest()));
        registerRequest.setSource(getSource());
        registerRequest.setChannel(TokenUtil.getRequest().getHeader("channel"));
        try {
            AESForWeixinGetPhoneNumber aes = new AESForWeixinGetPhoneNumber(registerRequest.getEncryptDataB64(),registerRequest.getSessionKeyB64(),registerRequest.getIvB64());
            WeixinPhoneDecryptInfo info = aes.decrypt();
            if(null == info){
                return CommonResult.failed("登录失败，请重新试！");
            }
            if(!WxConstants.WX_APPLET_APPID_TXG.equals(info.getWeixinWaterMark().getAppid())){
                return CommonResult.failed("APPID不正确，登录失败！");
            }
            registerRequest.setTelephone(info.getPhoneNumber());

        } catch (Exception e) {
            log.error("一键登录失败：{}",getExceptionToString(e));
            return CommonResult.failed("一键登录失败！");
        }
        return loginService.wxTokenLogin(registerRequest);
    }

}
